package com.tgy.myredis.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/***
 * @ClassName: RedisSentinelConfig
 * @Description: 主从模式redis配置
 * @Auther: tanggy3
 * @Date: 14:26 2022/7/27
 * @version : V1.0
 */
@Configuration
@ConfigurationProperties(prefix = "jedis")
@ConditionalOnProperty(prefix = "using", name = "redis", havingValue = "sentinel")
@Setter
@Getter
public class RedisSentinelConfig {
    private String masterName;
    private List<String> sentinelNodes;
    @Nullable
    private String password;
    @Nullable
    private int dbIndex;

    @Bean
    public JedisConnectionFactory redisConnectionFactory() {

        RedisSentinelConfiguration config = new RedisSentinelConfiguration();
        config.setMaster(masterName);

        Set<RedisNode> sn = new HashSet<>(sentinelNodes.size());
        sentinelNodes.forEach((s) -> sn.add(new RedisNode(s.split(":")[0], Integer.parseInt(s.split(":")[1]))));
        config.setSentinels(sn);

        if (!StringUtils.isEmpty(password)) {
            config.setPassword(RedisPassword.of(password));
        }
        config.setDatabase(dbIndex);
        JedisConnectionFactory factory = new JedisConnectionFactory(config);
        return factory;
    }

    @Bean
    public RedisTemplate<String, Object> registerRedisTemplate(JedisConnectionFactory factory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值（默认使用JDK的序列化方式）
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域，field,get和set,以及修饰符范围，ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型，类必须是非final修饰的，final修饰的类，比如String,Integer等会跑出异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);

        // 值采用json序列化
        redisTemplate.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        redisTemplate.setKeySerializer(new StringRedisSerializer());

        // 设置hash key 和value序列化模式
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(jacksonSeial);
        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }

}
